// pages/merchant/statistics/index.js
const apiService = require('../../../utils/api.js');
const amount = require('../../../utils/amount.js');

Page({
  data: {
    // 时间范围
    timeRange: 'today',
    startDate: '',
    endDate: '',
    
    // 核心指标（金额单位：分）
    coreMetrics: {
      revenue: 0,
      revenueDisplay: '0.00',
      revenueChange: 0,
      orders: 0,
      orderChange: 0,
      customers: 0,
      customerChange: 0,
      avgOrder: 0,
      avgOrderDisplay: '0.00',
      avgOrderChange: 0
    },
    
    // 订单类型统计（金额单位：分）
    orderTypeStats: {
      foster: 0,
      fosterAmount: 0,
      fosterAmountDisplay: '0.00',
      device: 0,
      deviceAmount: 0,
      deviceAmountDisplay: '0.00',
      service: 0,
      serviceAmount: 0,
      serviceAmountDisplay: '0.00',
      recharge: 0,
      rechargeAmount: 0,
      rechargeAmountDisplay: '0.00'
    },
    
    // 热门服务（revenue单位：分）
    popularServices: [],
    
    // 设备统计（revenue单位：分）
    deviceStats: [],
    
    // 加载状态
    isLoading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('数据统计页面加载', options);
    this.initDateRange();
    this.loadStatisticsData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadStatisticsData();
  },

  /**
   * 初始化日期范围
   */
  initDateRange() {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    this.setData({
      startDate: formatDate(yesterday),
      endDate: formatDate(today)
    });
  },

  /**
   * 时间范围改变
   */
  onTimeRangeChange(e) {
    const range = e.currentTarget.dataset.range;
    this.setData({ timeRange: range });
    this.loadStatisticsData();
  },

  /**
   * 开始日期改变
   */
  onStartDateChange(e) {
    this.setData({ startDate: e.detail.value });
    this.loadStatisticsData();
  },

  /**
   * 结束日期改变
   */
  onEndDateChange(e) {
    this.setData({ endDate: e.detail.value });
    this.loadStatisticsData();
  },

  /**
   * 加载统计数据
   */
  async loadStatisticsData() {
    this.setData({ isLoading: true });
    
    try {
      // 模拟统计数据，实际项目中应该调用API
      const mockData = this.generateMockStatisticsData();
      
      // 格式化显示数据
      const formatData = this.formatStatisticsData(mockData);
      
      this.setData({
        coreMetrics: formatData.coreMetrics,
        orderTypeStats: formatData.orderTypeStats,
        popularServices: formatData.popularServices,
        deviceStats: formatData.deviceStats
      });

      console.log('统计数据加载成功:', formatData);
      
    } catch (error) {
      console.error('加载统计数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  /**
   * 格式化统计数据，添加显示字段
   */
  formatStatisticsData(data) {
    return {
      coreMetrics: {
        ...data.coreMetrics,
        revenueDisplay: (data.coreMetrics.revenue / 100).toFixed(2),
        avgOrderDisplay: (data.coreMetrics.avgOrder / 100).toFixed(2)
      },
      orderTypeStats: {
        ...data.orderTypeStats,
        fosterAmountDisplay: (data.orderTypeStats.fosterAmount / 100).toFixed(2),
        deviceAmountDisplay: (data.orderTypeStats.deviceAmount / 100).toFixed(2),
        serviceAmountDisplay: (data.orderTypeStats.serviceAmount / 100).toFixed(2),
        rechargeAmountDisplay: (data.orderTypeStats.rechargeAmount / 100).toFixed(2)
      },
      popularServices: data.popularServices.map(item => ({
        ...item,
        revenueDisplay: (item.revenue / 100).toFixed(2)
      })),
      deviceStats: data.deviceStats.map(item => ({
        ...item,
        revenueDisplay: (item.revenue / 100).toFixed(2)
      }))
    };
  },

  /**
   * 生成模拟统计数据（金额以分为单位）
   */
  generateMockStatisticsData() {
    const { timeRange } = this.data;
    
    // 根据时间范围生成不同的数据
    let multiplier = 1;
    switch (timeRange) {
      case 'today':
        multiplier = 1;
        break;
      case 'week':
        multiplier = 7;
        break;
      case 'month':
        multiplier = 30;
        break;
      case 'custom':
        multiplier = 7; // 自定义范围，假设7天
        break;
    }

    // 基础数据（原先为元，这里统一转换为分）
    const toCent = (yuan) => Math.floor(yuan * 100);

    return {
      coreMetrics: {
        revenue: toCent(Math.floor(1250 * multiplier)),
        revenueChange: Math.floor(Math.random() * 20) - 10, // -10% 到 +10%
        orders: Math.floor(45 * multiplier),
        orderChange: Math.floor(Math.random() * 15) - 5, // -5% 到 +10%
        customers: Math.floor(28 * multiplier),
        customerChange: Math.floor(Math.random() * 12) - 3, // -3% 到 +9%
        avgOrder: toCent(Math.floor(88 * (1 + (Math.random() - 0.5) * 0.2))), // 88 ± 20%（分）
        avgOrderChange: Math.floor(Math.random() * 8) - 2 // -2% 到 +6%
      },
      
      orderTypeStats: {
        foster: Math.floor(12 * multiplier),
        fosterAmount: toCent(Math.floor(2400 * multiplier)),
        device: Math.floor(18 * multiplier),
        deviceAmount: toCent(Math.floor(900 * multiplier)),
        service: Math.floor(15 * multiplier),
        serviceAmount: toCent(Math.floor(1800 * multiplier)),
        recharge: Math.floor(8 * multiplier),
        rechargeAmount: toCent(Math.floor(1600 * multiplier))
      },
      
      popularServices: [
        {
          serviceId: 'service_001',
          name: '专业洗浴服务',
          description: '洗浴+吹干+基础护理',
          orderCount: Math.floor(25 * multiplier),
          revenue: toCent(Math.floor(2200 * multiplier))
        },
        {
          serviceId: 'service_002',
          name: '宠物寄养服务',
          description: '单间寄养，含基础护理',
          orderCount: Math.floor(12 * multiplier),
          revenue: toCent(Math.floor(2400 * multiplier))
        },
        {
          serviceId: 'service_003',
          name: '设备使用服务',
          description: '洗浴设备使用',
          orderCount: Math.floor(18 * multiplier),
          revenue: toCent(Math.floor(900 * multiplier))
        },
        {
          serviceId: 'service_004',
          name: '美容造型服务',
          description: '全身美容+造型设计',
          orderCount: Math.floor(8 * multiplier),
          revenue: toCent(Math.floor(1200 * multiplier))
        },
        {
          serviceId: 'service_005',
          name: '充值服务',
          description: '账户余额充值',
          orderCount: Math.floor(15 * multiplier),
          revenue: toCent(Math.floor(3000 * multiplier))
        }
      ],
      
      deviceStats: [
        {
          deviceId: 'device_001',
          deviceName: '洗浴设备A',
          location: '1号房间',
          useCount: Math.floor(25 * multiplier),
          totalHours: Math.floor(18 * multiplier),
          revenue: toCent(Math.floor(1250 * multiplier))
        },
        {
          deviceId: 'device_002',
          deviceName: '烘干设备B',
          location: '2号房间',
          useCount: Math.floor(20 * multiplier),
          totalHours: Math.floor(15 * multiplier),
          revenue: toCent(Math.floor(1000 * multiplier))
        },
        {
          deviceId: 'device_003',
          deviceName: '美容设备C',
          location: '3号房间',
          useCount: Math.floor(12 * multiplier),
          totalHours: Math.floor(8 * multiplier),
          revenue: toCent(Math.floor(600 * multiplier))
        }
      ]
    };
  },

  /**
   * 刷新数据
   */
  async onRefresh() {
    wx.showLoading({ title: '刷新中...' });
    
    try {
      await this.loadStatisticsData();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    } catch (error) {
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 导出数据
   */
  onExportData() {
    wx.showActionSheet({
      itemList: ['导出Excel', '导出PDF', '分享数据'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            wx.showToast({
              title: 'Excel导出功能开发中',
              icon: 'none'
            });
            break;
          case 1:
            wx.showToast({
              title: 'PDF导出功能开发中',
              icon: 'none'
            });
            break;
          case 2:
            wx.showToast({
              title: '分享功能开发中',
              icon: 'none'
            });
            break;
        }
      }
    });
  }
});